package com.yangoxix.lovegoing.service;

import com.yangoxix.lovegoing.pojo.Image;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * The type Image service.
 */
@Service
public class ImageService {


    /**
     * Save audit image.//    保存未审核活动的图片
     *
     * @param name the name
     * @param url  the url
     */

    public void SaveAuditImage(String name, String url) {
        Image image = new Image();
        image.setActivityname("未审核|" + name);
        image.setImgurl(url);
        image.insert();
    }


    /**
     * Delete image by name.//删除图片
     *
     * @param name the name
     */

    public void DeleteImageByName(String name) {
        Image image = new Image();
        boolean name1 = image.deleteById("name");
        if (name1) {
            System.out.println("ImageService：删除图片成功");
        } else {
            System.out.println("ImageService：删除图片失败");
        }


    }

    /**
     * Save imag string.// 把图片保存到本地
     *
     * @param file the file
     * @return the string
     */

    public String saveImag(MultipartFile file) {
        String filename = file.getOriginalFilename();
        if (!file.isEmpty()) {
            //获取文件名

            try {
                String dirpath = System.getProperty("user.dir") + "/webapp/image/";
                File dirfile = new File(dirpath);
                if (!dirfile.exists()) {
                    dirfile.mkdirs();
                }
                String fileurl = dirpath + filename;
                System.out.println(fileurl);
                File f = new File(fileurl);
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f));
                if (!f.exists()) {
                    try {
                        f.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                out.write(file.getBytes());
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("上传失败，因为文件是空的.");
        }
        return "/image/"+filename;
    }

    public boolean deleteImage(String urlString){
        //删除本地文件   /image/FbTfx9sZGBPVa03ecbbba1f02037fb260fa09084439b.jpg
        if (urlString == null) {
            return true;
        }
        String dirpath = System.getProperty("user.dir") + "/webapp/image/";
        String substring = urlString.substring(7);
        File file = new File(dirpath + substring);
        return file.delete();
    }
}
